﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class ShowProcessTypeHandler : IRequestHandler<ShowProcessTypeCommand, ApiPageing<ProcessType>>
    {
        private readonly IProcessRepository<ProcessType> _processRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddProcessTypeHandler> _logger;

        public ShowProcessTypeHandler(IProcessRepository<ProcessType> processRepository, IMapper mapper, ILogger<AddProcessTypeHandler> logger)
        {
            _processRepository = processRepository;
            this.mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 查询工序分类分页数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPageing<ProcessType>> Handle(ShowProcessTypeCommand request, CancellationToken cancellationToken)
        {
            ApiPageing<ProcessType> result = new ApiPageing<ProcessType>();
            var list = _processRepository.GetAllAsync().Where(x => x.IsDelete == false);
            
            if(!string.IsNullOrEmpty(request.ProcessTypeCode))
            {
                list = list.Where(x => x.ProcessTypeCode != null && x.ProcessTypeCode.Contains(request.ProcessTypeCode));
            }
            if (!string.IsNullOrEmpty(request.ProcessTypeName))
            {
                list = list.Where(x => x.ProcessTypeName != null && x.ProcessTypeName.Contains(request.ProcessTypeName));
            }

         
            var query = list.OrderByDescending(x => x.Id)
                           .Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize)
                           .ToList();
            var total = query.Count();

            result.TotalCount = total;
            result.TotalPage = (int)Math.Ceiling((double)total / request.PageSize);
            result.Code = ErrorStatus.Success;
            result.PageData = query;
            result.Message = "获取工序分页数据成功";
            return result;
        }
    }
}
